package com.example.lianjuan.Presenter.impl.impl;

import android.util.Log;

import com.example.lianjuan.Model.API;
import com.example.lianjuan.Model.domain.Histories;
import com.example.lianjuan.Model.domain.SearchResult;
import com.example.lianjuan.Presenter.impl.ISearchPresenter;
import com.example.lianjuan.Utils.JsonCacheUtil;
import com.example.lianjuan.Utils.LogUtils;
import com.example.lianjuan.Utils.RecommendPageUtil;
import com.example.lianjuan.Utils.RetrofitManang;
import com.example.lianjuan.Utils.ToastUtil;
import com.example.lianjuan.View.ISearchPageCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPresenterImpl implements ISearchPresenter {
    private ISearchPageCallback callback;
    private int mCurrentPage = DEFAULT_PAGE;
    private final API mApi;
    private static final int DEFAULT_PAGE = 0;
    private String mCurrentKeyword = null;
    private final JsonCacheUtil mJsonCacheUtil;
    private static final String KEY_HISTORIES = "key_histories";
    private static final int DEFAULT_SIZE = 10;
    private int HISTORIES_SIZE = DEFAULT_SIZE;

    public SearchPresenterImpl() {
        Retrofit retrofit = RetrofitManang.getRetrofitManang().getRetrofit();
        mApi = retrofit.create(API.class);
        mJsonCacheUtil = JsonCacheUtil.getInstance();
    }

    /**
     * 获取历史数据
     */
    @Override
    public void getHistories() {
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        //历史数据为不空和有数据
        if (histories != null &&
                histories.getHistories() != null &&
                histories.getHistories().size() > 0) {
            List<String> historiesList = histories.getHistories();
            if (callback != null) {
                callback.onHistoriesLoaded(historiesList);
            }
        }
    }

    /**
     * 删除历史数据
     */
    @Override
    public void delHistories() {
        mJsonCacheUtil.delCache(KEY_HISTORIES);

    }

    /**
     * 添加历史数据
     */
    private void saveHistories(String history) {
        //数据库里是否有相同的,有先删除在添加
        List<String> historiesList = null;
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        if (histories != null && histories.getHistories() != null) {
            historiesList = histories.getHistories();
            if (historiesList.contains(history)) {
                historiesList.remove(history);
            }
        } else {
            historiesList = new ArrayList<>();
        }
        //去重完成
        //处理没数据的情况
        if (histories == null) {
            histories = new Histories();
        }
        //添加记录
        historiesList.add(history);
        //对个数进行限制
        if (historiesList.size() > HISTORIES_SIZE) {
            historiesList.subList(0, HISTORIES_SIZE);
        }
        histories.setHistories(historiesList);
        //保存记录
        mJsonCacheUtil.saveCache(KEY_HISTORIES, histories);
    }

    @Override
    public void doSearch(String keyword) {
        //保存数据
        if (this.mCurrentKeyword == null || !this.mCurrentKeyword.equals(keyword)) {
            this.saveHistories(keyword);
            this.mCurrentKeyword = keyword;
        }
        //给加载更多使用
        if (callback != null) {
            callback.onLoadLoading();
        }
        Call<SearchResult> task = mApi.onSearch(mCurrentPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    handleSuccessLoaded(response.body());
                } else {
                    handleError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                handleError();
            }
        });
    }

    /**
     * 请求正确处理
     *
     * @param result
     */
    private void handleSuccessLoaded(SearchResult result) {
        if (callback != null) {
            if (!isEmpty(result)) {
                callback.onSearchSuccess(result);
            } else {
                callback.onLoadEmpty();
            }
        }

    }

    private boolean isEmpty(SearchResult result) {
        if (result == null
                && result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 请求错误处理
     */
    private void handleError() {
        if (callback != null) {
            callback.onError();
        }
    }

    @Override
    public void research() {
        if (mCurrentKeyword == null) {
            if (callback != null) {
                callback.onLoadEmpty();
            }
        }
        doSearch(mCurrentKeyword);
    }

    @Override
    public void loaderMore() {
        //页码加1
        mCurrentPage++;
        if (mCurrentKeyword == null) {
            if (callback != null) {
                callback.onLoadEmpty();
            }
        }
        Call<SearchResult> task = mApi.onSearch(mCurrentPage, mCurrentKeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    handleSuccessMoreLoaded(response.body());
                } else {
                    handleLoadMoreError();
                    //加载失败页码--
                    mCurrentPage--;
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                handleLoadMoreError();
                //加载失败页码--
                mCurrentPage--;
            }
        });
    }

    /**
     * 搜更多内容
     *
     * @param result
     */
    private void handleSuccessMoreLoaded(SearchResult result) {
        if (callback != null) {
            if (!isEmpty(result)) {
                //数据不为空
                callback.onLoadedMord(result);
            } else {
                callback.onLoadedMordEmpty();
            }
        }
    }

    /**
     * 加载更多失败
     */
    private void handleLoadMoreError() {
        if (callback != null) {
            callback.onLoadedMordError();
        }
    }

    @Override
    public void getRecommendWords() {
        //推荐商品词接口未返回数据，自己创建
        List<String> recommendPage = RecommendPageUtil.getRecommendPage();
        callback.onRecommendWordLoaded(recommendPage);
    }

    @Override
    public void registerViewCallback(ISearchPageCallback callback) {
        this.callback = callback;
    }

    @Override
    public void unregisterViewCallback(ISearchPageCallback callback) {
        this.callback = null;
    }
}
